package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo getCaptcha() {
        //创建一个尺寸为130x48、包含4个字符的验证码图片对象
        SpecCaptcha specCaptcha = new SpecCaptcha(130,48,4);
        //该行代码设置验证码字符类型为默认类型（数字和字母混合）
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        //获取验证码文本内容并转换为小写，用于后续的验证码校验或存储操作
        String code = specCaptcha.text().toLowerCase();
        //该行代码生成一个唯一的Redis键，用于存储管理员登录时的验证码信息，格式为前缀加随机UUID。
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        //将生成的验证码图片转换为Base64编码字符串，用于前端展示。
        String image = specCaptcha.toBase64();
        //该行代码将验证码的值（code）存储到 Redis 中，使用生成的 key 作为键，并设置过期时间为 60 秒，用于管理员登录时的验证码校验。
        stringRedisTemplate.opsForValue().set(key, code,60,TimeUnit.SECONDS);
        return new CaptchaVo(image, key);
    }

    @Override
    public String login(LoginVo loginVo) {
        //判断验证码是否为空
        String captchaCode = loginVo.getCaptchaCode();
        String captchaKey = loginVo.getCaptchaKey();
        System.out.println("captchaKey = " + captchaKey);
        if(!StringUtils.hasText(captchaCode)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //查询code是否为空，空则是过期
        //从Redis中根据验证码的key获取之前存储的验证码code
        String code = stringRedisTemplate.opsForValue().get(captchaKey);
        System.out.println(code);
        if(code == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //判断是否相同
        if(!code.equals(loginVo.getCaptchaCode().toLowerCase())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //username查询数据库
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserMapper.selectOne(queryWrapper);
        if(systemUser==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //查看用户状态
        if(systemUser.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //查询密码是否一致
        if(!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        return JwtUtil.createToken(systemUser.getId(),systemUser.getUsername());
    }

//    @Override
//    public SystemUser getUserInfo(Long id) {
//        return systemUserMapper.selectById(id);
//    }


    @Override
    public SystemUserInfoVo getSystemUserInfoById(Long id) {
        SystemUser systemUser = systemUserMapper.selectById(id);
        SystemUserInfoVo systemUserInfoVo =new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;

    }
}
